package com.gakj.truck.third.api.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gakj.truck.third.api.mapper.TruckOumanMapper;
import com.gakj.truck.third.api.ouman.OumanService;
import com.gakj.truck.third.core.domain.*;
import com.gakj.truck.third.core.domain.area.ShtCity;
import com.gakj.truck.third.core.domain.area.ShtDistrict;
import com.gakj.truck.third.core.domain.area.ShtProvince;
import com.gakj.truck.third.core.enums.EnumPlatform;
import com.gakj.truck.third.core.enums.EnumTruckPublishStatus;
import com.gakj.truck.third.core.utils.DateUtil;
import com.gakj.truck.third.core.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.gakj.truck.third.core.utils.DateUtil.defaultFormatStringToDate;

/**
 * Created by gc on 2016/5/16.
 */
@Service public class TruckOumanService {

    private static final String DATA = "data";
    private static final String SOUCE_OUMAN = "0";
    private static final String NOT_SAVE = "0";
    private static final String HAS_SAVE = "1";

    private static final String IMG_PREFIX = "http://www.2scv.cn";

    private static final Logger LOGGER = LoggerFactory.getLogger(TruckOumanService.class);

    @Autowired TruckOumanMapper truckOumanMapper;

    @Autowired OumanService oumanService;

    @Autowired AreaService areaService;

    @Autowired TruckDtoService truckDtoService;

    @Autowired TruckService truckService;

    @Autowired TruckModelService modelService;

    @Autowired TruckBrandService brandService;

    @Autowired TruckImgDtoService imgDtoService;


    public TruckOuman getSingle(Long id){
        return truckOumanMapper.getById(id);
    }

    /**
     * 保存到中间表的时候,同步到蜗牛数据库中
     *
     * @param jsonString
     */
    public JSONObject saveOrUpdate(String jsonString) throws Exception {

        JSONObject result = new JSONObject();
        //    TODO 测试用的
        //        JSONObject oumanTruckList = oumanService.getOumanTruckList(1);
        //        jsonString = JSON.toJSONString(oumanTruckList);

        //将传递过来的json字符串转换成truckouman对象
        JSONObject json = JSONObject.parseObject(jsonString);
        //        JSONArray json = oumanTruckList.getJSONArray("data");
        //        TruckOuman transform = transform((JSONObject) json.get(0));
        TruckOuman transform = testObject(json);
        //通过ouman的车辆ID获取保存到中间表中的数据
        Long truckid = transform.getTruckId();
        TruckOuman truckOuman = getByOumanid(truckid);
        //数据库中没有该条信息
        if (truckOuman == null) {
            try {

                //获得欧曼数据保存后的新ID
                save(transform);
                Long newtruckid = transform.getId();
                //获取保存后生成的新数据
                truckOuman = getById(newtruckid);
                LOGGER.info("保存欧曼数据成功!");
            } catch (Exception ex) {
                ex.printStackTrace();
                LOGGER.error("保存欧曼数据失败!");
            }

        } else {
            //数据库有这条信息
            copy(transform, truckOuman);
            try {
                update(truckOuman);
                LOGGER.info("更新欧曼数据成功!");
            } catch (Exception ex) {
                ex.printStackTrace();
                LOGGER.error("更新欧曼数据失败!");
            }
        }

        try {
            saveOrUpdateToSnail(truckOuman);
            LOGGER.info("欧曼数据同步到蜗牛数据库中成功!!!!");
            result = RequestUtils.success("");
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("欧曼数据同步到蜗牛数据库中失败!!!!");
            result = RequestUtils.failure("保存失败!" + ex.getMessage());
        }
        return result;
    }

    /**
     * 保存到中间表的时候,同步到蜗牛数据库中
     *
     * @param day
     */
    public JSONObject saveOrUpdate(int day) throws Exception {

        JSONObject result = new JSONObject();
        JSONObject oumanTruckList = oumanService.getOumanTruckList(day);
        JSONArray json = oumanTruckList.getJSONArray("data");
        if (json != null && json.size() > 0) {
            for (Object aJson : json) {
                JSONObject o = (JSONObject) aJson;
                TruckOuman transform = testObject(o);
                //通过ouman的车辆ID获取保存到中间表中的数据
                Long truckid = transform.getTruckId();
                TruckOuman truckOuman = getByOumanid(truckid);
                //数据库中没有该条信息
                if (truckOuman == null) {
                    try {
                        //获得欧曼数据保存后的新ID
                        save(transform);
                        Long newtruckid = transform.getId();
                        //获取保存后生成的新数据
                        truckOuman = getById(newtruckid);
                        LOGGER.info("保存欧曼数据成功!");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        LOGGER.error("保存欧曼数据失败!");
                    }

                } else {
                    //数据库有这条信息
                    copy(transform, truckOuman);
                    try {
                        update(truckOuman);
                        LOGGER.info("更新欧曼数据成功!");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        LOGGER.error("更新欧曼数据失败!");
                    }
                }

                try {
                    saveOrUpdateToSnail(truckOuman);
                    LOGGER.info("欧曼数据同步到蜗牛数据库中成功!!!!");
                    result = RequestUtils.success("");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    LOGGER.error("欧曼数据同步到蜗牛数据库中失败!!!!");
                    result = RequestUtils.failure("保存失败!" + ex.getMessage());
                }
            }
        }
        return result;
    }


    public Long save(TruckOuman truckOuman) {
        return truckOumanMapper.save(truckOuman);
    }

    public TruckOuman getById(Long id) {
        return truckOumanMapper.getById(id);
    }

    public void update(TruckOuman truckOuman) {
        truckOumanMapper.update(truckOuman);
    }

    public TruckOuman getByOumanid(Long truckid) {
        return truckOumanMapper.getByOumanid(truckid);
    }


    public void batchSave(List<TruckOuman> list) {
        truckOumanMapper.batchSave(list);
    }

    public JSONObject getTurckFromOuman(int day) {
        JSONObject message = new JSONObject();
        JSONObject result = oumanService.getOumanTruckList(day);
        Date endDate = new Date();
        LOGGER.info("获取到的数据:" + result.size());

        List<TruckOuman> list = new ArrayList<>();
        if (result.size() > 0) {
            JSONArray data = result.getJSONArray(DATA);
            if (data != null && data.size() > 0) {
                for (Object aData : data) {
                    JSONObject json = (JSONObject) aData;
                    TruckOuman transform = transform(json);
                    list.add(transform);
                }
            }
            if (list.size() > 0) {
                try {
                    //                    batchSave(list);
                    for (TruckOuman ouman : list) {
                        //去重操作
                        //                        TruckOuman truckOuman = this.getByOumanid(ouman.getTruckId());
                        TruckOuman truckOuman = getTruckOumanByTruckIdAndSource(ouman.getTruckId(), ouman.getSource());
                        if (truckOuman == null) {
                            Date startDate = null;
                            if (ouman.getCreatetime().length() <= 10) {
                                String dateString = ouman.getCreatetime() + " 00:00:00";
                                startDate = defaultFormatStringToDate(dateString);
                            } else {
                                startDate = defaultFormatStringToDate(ouman.getCreatetime());
                            }
                            if (DateUtil.twoDayDiffence(startDate, endDate) <= 1) {
                                this.save(ouman);
                                this.saveOrUpdateToSnail(ouman, 0);
                            }

                        }
                        //                        else {
                        //                            TruckOuman copy = copy(ouman, truckOuman);
                        //                            this.update(copy);
                        //                            this.saveOrUpdateToSnail(copy, 1);
                        //                        }
                    }
                    message.put("resMsg", "保存欧曼信息到蜗牛数据中成功!");
                    message.put("resCode", "1");
                } catch (Exception e) {
                    e.printStackTrace();
                    message.put("resMsg", "保存欧曼信息到蜗牛数据库中失败!" + e.getMessage());
                    message.put("resCode", "0");
                }
            }
        } else {
            message.put("resMsg", "获取欧曼车辆信息失败!");
            message.put("resCode", "0");
        }
        return message;
    }

    /**
     * 批量保存从欧曼获取的车辆数据
     */
    public void batchSave() {
        getTurckFromOuman(1);
    }

    /**
     * 处理历史数据
     *
     * @throws Exception
     */
    public void dealOldData() throws Exception {

        List<TruckOuman> list = truckOumanMapper.getNotSaveData();

        if (list != null && list.size() > 0) {
            for (TruckOuman ouman : list) {
                Truck truck = transformToTruck(ouman);
                truckService.save(truck);
                saveInfoid(truck);
                saveTruckImages(ouman.getImgList(), truck);
                ouman.setHasSave("1");
                ouman.setEnterupdatetime(new Date());
                ouman.setRelationId(truck.getId());
                truckOumanMapper.update(ouman);
            }
        }
    }

    /**
     * 复制类属性
     *
     * @param source
     * @param target
     */
    private TruckOuman copy(TruckOuman source, TruckOuman target) {
        target.setEntercreatetime(new Date());
        target.setContactname(source.getContactname());
        target.setContacttel(source.getContacttel());
        target.setCreatetime(source.getCreatetime());
        target.setUpdatetime(source.getUpdatetime());
        target.setAreaname(source.getAreaname());
        target.setModelName(source.getModelName());
        target.setFirsthand(source.getFirsthand());
        target.setImgList(source.getImgList());
        target.setEmission(source.getEmission());
        target.setCarstatus(source.getCarstatus());
        target.setUsername(source.getUsername());
        target.setUserType(source.getUserType());
        target.setTitle(source.getTitle());
        target.setProvinceName(source.getProvinceName());
        target.setVin(source.getVin());
        target.setPower(source.getPower());
        target.setShowmileage(source.getShowmileage());
        target.setImgThumbnail(source.getImgThumbnail());
        target.setBrandName(source.getBrandName());
        target.setViewcount(source.getViewcount());
        target.setPrice(source.getPrice());
        target.setOwnerdepict(source.getOwnerdepict());
        target.setColor(source.getColor());
        target.setCityName(source.getCityName());
        target.setCardtime(source.getCardtime());
        return target;

    }

    private Truck transformToTruck(TruckOuman ouman) throws Exception {
        Date createtime = formatDate(ouman.getCreatetime());
        Date updatetime = formatDate(ouman.getUpdatetime());
        Date cardtime = formatDate(ouman.getCardtime());
        String contacttel = ouman.getContacttel();
        String contactname = ouman.getContactname();
        //        String carstatus = ouman.getCarstatus();
        String color = ouman.getColor();
        String emission = ouman.getEmission();
        String firsthand = ouman.getFirsthand();
        String viewcount = ouman.getViewcount();
        String power = ouman.getPower();
        String ownerdepict = ouman.getOwnerdepict();
        String title = ouman.getTitle();
        String showmileage = ouman.getShowmileage();
        String seecarplace = ouman.getSeecarplace();
        Float price = ouman.getPrice();
        String vin = ouman.getVin();
        String username = ouman.getUsername();
        String userType = ouman.getUserType();
        String cityName = ouman.getCityName();
        String areaname = ouman.getAreaname();
        String provinceName = ouman.getProvinceName();
        ShtCity shtCity = areaService.getShtCityByname(cityName);
        ShtProvince shtProvince = areaService.getProvinceByname(provinceName);
        ShtDistrict shtDistrict = areaService.getShtDistrictByname(areaname, shtCity.getId(), shtProvince.getId());
        String brandName = ouman.getBrandName();
        String modelName = ouman.getModelName();
        List<TruckBrand> brands = brandService.getByName(brandName);
        List<TruckModel> models = modelService.getByName(modelName);
        String imgThumbnail = ouman.getImgThumbnail();
        String imgList = ouman.getImgList();


        Truck dto = new Truck();
        dto.setCardtime(cardtime);
        dto.setVin(vin);
        dto.setCreatetime(createtime);
        dto.setUpdatetime(updatetime);
        dto.setContacttel(contacttel);
        dto.setContacttname(contactname);
        dto.setCarstatus(EnumTruckPublishStatus.NEVERAUDIT.getCode());
        dto.setColor(color);
        dto.setPrice(price);
        dto.setViewcount(Integer.valueOf(viewcount));
        dto.setTitle(title);
        dto.setEmission(emission);
        dto.setShowmileage(Float.valueOf(showmileage));
        dto.setFirsthand(firsthand);
        dto.setPower(power);
        dto.setSeecarplace(seecarplace);
        dto.setOwnerdepict(ownerdepict);
        if (brands != null && brands.size() > 0) {
            dto.setBrandid(brands.get(0).getId());
        }
        if (models != null && models.size() > 0) {
            dto.setModel(models.get(0).getId());
        }
        if (shtCity != null) {
            dto.setCity(shtCity.getId());
        }
        if (shtProvince != null) {
            dto.setProvinces(shtProvince.getId());
        }
        if (shtDistrict != null) {
            dto.setAreaid(shtDistrict.getId());
        }

        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(brandName)) {
            sb.append(brandName);
        }
        if (StringUtils.isNotBlank(modelName)) {
            sb.append(modelName);
        }
        if (cardtime != null) {
            sb.append(cardtime);
        }
        if (price != null) {
            sb.append(price + "");
        }
        if (StringUtils.isNotBlank(showmileage)) {
            sb.append(showmileage);
        }
        //        sb.append(brandName).append(modelName).append(cardtime).append(price).append(showmileage);
        dto.setKeyword(sb.toString());
        dto.setPlatform(EnumPlatform.DATA_OUMAN.getCode());
        return dto;
    }

    private void saveInfoid(Truck tk) {
        String infoid = DateUtil.formatDateToString(tk.getCreatetime(), "yyMMdd") + tk.getId().toString()
                .substring(tk.getId().toString().length() - 4, tk.getId().toString().length());
        tk.setInfoid(infoid);
        String keyword = tk.getKeyword();
        tk.setKeyword(infoid + keyword);
        truckService.update(tk);
    }

    private TruckOuman transform(JSONObject result) {

        String modelname = result.getString("modelname");
        String firsthand = result.getString("firsthand");
        String updatetime = result.getString("updatetime");
        String imglist = result.getString("imglist");
        String emission = result.getString("emission");
        String tel = result.getString("tel");
        String carstatus = result.getString("carstatus");
        String contact = result.getString("contact");
        String createtime = result.getString("createtime");
        Long id = result.getLong("id");
        String username = result.getString("username");
        String title = result.getString("title");
        String provincename = result.getString("provincename");
        String vin = result.getString("vin");
        String power = result.getString("power");
        String showmileage = result.getString("showmileage");
        String imgthumbnail = result.getString("imgthumbnail");
        String brandname = result.getString("brandname");
        String usertype = result.getString("usertype");
        String viewcount = result.getString("viewcount");
        Float price = result.getFloat("price");
        String ownerdepict = result.getString("ownerdepict");
        String address = result.getString("address");
        String color = result.getString("color");
        String cityname = result.getString("cityname");
        String cardtime = result.getString("cardtime");
        String areaname = result.getString("areaname");


        TruckOuman ouman = new TruckOuman();

        ouman.setTruckId(id);
        ouman.setEntercreatetime(new Date());
        ouman.setContactname(contact);
        ouman.setContacttel(tel);
        ouman.setCreatetime(createtime);
        ouman.setUpdatetime(updatetime);
        ouman.setAreaname(areaname);
        ouman.setModelName(modelname);
        ouman.setFirsthand(firsthand);
        ouman.setImgList(imglist);
        ouman.setEmission(emission);
        ouman.setCarstatus(carstatus);
        ouman.setUsername(username);
        ouman.setUserType(usertype);
        ouman.setTitle(title);
        ouman.setProvinceName(provincename);
        ouman.setVin(vin);
        ouman.setPower(power);
        ouman.setShowmileage(showmileage);
        ouman.setImgThumbnail(IMG_PREFIX + imgthumbnail);
        ouman.setBrandName(brandname);
        ouman.setViewcount(viewcount);
        ouman.setPrice(price);
        ouman.setOwnerdepict(ownerdepict);
        ouman.setColor(color);
        ouman.setCityName(cityname);
        ouman.setCardtime(cardtime);

        ouman.setEnterupdatetime(new Date());
        ouman.setSource(SOUCE_OUMAN);
        ouman.setHasSave(NOT_SAVE);
        return ouman;
    }


    private void saveOrUpdateToSnail(TruckOuman ouman, int flag) throws Exception {

        Date createtime = formatDate(ouman.getCreatetime());
        Date updatetime = formatDate(ouman.getUpdatetime());
        Date cardtime = formatDate(ouman.getCardtime());
        String contacttel = ouman.getContacttel();
        String contactname = ouman.getContactname();
        String carstatus = ouman.getCarstatus();
        String color = ouman.getColor();
        String emission = ouman.getEmission();
        String firsthand = ouman.getFirsthand();
        String viewcount = ouman.getViewcount();
        String power = ouman.getPower();
        String ownerdepict = ouman.getOwnerdepict();
        String title = ouman.getTitle();
        String showmileage = ouman.getShowmileage();
        String seecarplace = ouman.getSeecarplace();
        Float price = ouman.getPrice();
        String vin = ouman.getVin();

        String username = ouman.getUsername();
        String userType = ouman.getUserType();

        String cityName = ouman.getCityName();
        String areaname = ouman.getAreaname();
        String provinceName = ouman.getProvinceName();
        ShtCity shtCity = areaService.getShtCityByname(cityName);
        ShtProvince shtProvince = areaService.getProvinceByname(provinceName);
        ShtDistrict shtDistrict = areaService.getShtDistrictByname(areaname, shtCity.getId(), shtProvince.getId());

        String brandName = ouman.getBrandName();
        String modelName = ouman.getModelName();
        List<TruckBrand> brands = brandService.getByName(brandName);
        List<TruckModel> models = modelService.getByName(modelName);


        String imgThumbnail = ouman.getImgThumbnail();
        String imgList = ouman.getImgList();
        Truck dto = new Truck();

        Long newid = null;

        if (flag == 1) { //已保存到蜗牛数据库中
            Long relationId = ouman.getRelationId(); //获取蜗牛数据库中对应的车辆ID
            dto = truckService.get(relationId);
            dto.setCardtime(cardtime != null ? cardtime : null);
            dto.setVin(vin);
            dto.setCreatetime(createtime);
            dto.setUpdatetime(updatetime);
            dto.setContacttel(contacttel);
            dto.setContacttname(contactname);
            dto.setCarstatus(EnumTruckPublishStatus.NEVERAUDIT.getCode());
            dto.setColor(color);
            dto.setPrice(price);
            dto.setViewcount(Integer.valueOf(viewcount));
            dto.setTitle(title);
            dto.setEmission(emission);
            dto.setShowmileage(Float.valueOf(showmileage));
            dto.setFirsthand(firsthand);
            dto.setPower(power);
            dto.setSeecarplace(seecarplace);
            dto.setOwnerdepict(ownerdepict);
            if (brands != null && brands.size() > 0) {
                dto.setBrandid(brands.get(0).getId());
            }
            if (models != null && models.size() > 0) {
                dto.setModel(models.get(0).getId());
            }
            dto.setCity(shtCity.getId());
            dto.setProvinces(shtProvince != null ? shtProvince.getId() : null);
            dto.setAreaid(shtDistrict != null ? shtDistrict.getId() : null);
            StringBuilder sb = new StringBuilder();
            sb.append(brandName).append(modelName).append(cardtime).append(price).append(showmileage);
            dto.setKeyword(sb.toString());
            dto.setPlatform(EnumPlatform.DATA_OUMAN.getCode());
            //            truckService.save(dto);
            truckService.update(dto);
            newid = dto.getId();
            ouman.setEnterupdatetime(new Date());
            ouman.setHasSave(HAS_SAVE);
            truckOumanMapper.update(ouman);
        } else {
            dto = transformToTruck(ouman);
            truckService.save(dto);
            newid = dto.getId();
            ouman.setEnterupdatetime(new Date());
            ouman.setRelationId(newid);
            ouman.setHasSave(HAS_SAVE);
            ouman.setEnterupdatetime(new Date());
            truckOumanMapper.update(ouman);
        }

        Truck tk = truckService.get(newid);
        if (tk != null) {
            saveInfoid(tk);
            saveTruckImages(imgList, tk);
        }
    }

    private void saveOrUpdateToSnail(TruckOuman ouman) throws Exception {

        Date createtime = formatDate(ouman.getCreatetime());
        Date updatetime = formatDate(ouman.getUpdatetime());
        Date cardtime = formatDate(ouman.getCardtime());
        String contacttel = ouman.getContacttel();
        String contactname = ouman.getContactname();
        String carstatus = ouman.getCarstatus();
        String color = ouman.getColor();
        String emission = ouman.getEmission();
        String firsthand = ouman.getFirsthand();
        String viewcount = ouman.getViewcount();
        String power = ouman.getPower();
        String ownerdepict = ouman.getOwnerdepict();
        String title = ouman.getTitle();
        String showmileage = ouman.getShowmileage();
        String seecarplace = ouman.getSeecarplace();
        Float price = ouman.getPrice();
        String vin = ouman.getVin();

        if (StringUtils.isNotBlank(vin) && vin.contains(",")) {
            vin = vin.substring(0, vin.indexOf(","));
        }

        String username = ouman.getUsername();
        String userType = ouman.getUserType();

        String cityName = ouman.getCityName();
        String areaname = ouman.getAreaname();
        String provinceName = ouman.getProvinceName();
        ShtCity shtCity = areaService.getShtCityByname(cityName);
        ShtProvince shtProvince = areaService.getProvinceByname(provinceName);
        ShtDistrict shtDistrict = areaService.getShtDistrictByname(areaname, shtCity.getId(), shtProvince.getId());

        String brandName = ouman.getBrandName();
        String modelName = ouman.getModelName();
        List<TruckBrand> brands = brandService.getByName(brandName);
        List<TruckModel> models = modelService.getByName(modelName);


        String imgThumbnail = ouman.getImgThumbnail();
        String imgList = ouman.getImgList();
        Truck dto = new Truck();

        Long newid = null;

        if (ouman.getHasSave().equals("1")) { //已保存到蜗牛数据库中
            Long relationId = ouman.getRelationId(); //获取蜗牛数据库中对应的车辆ID
            dto = truckService.get(relationId);
            dto.setCardtime(cardtime != null ? cardtime : null);
            dto.setVin(vin);
            dto.setCreatetime(createtime);
            dto.setUpdatetime(updatetime);
            dto.setContacttel(contacttel);
            dto.setContacttname(contactname);
            dto.setCarstatus(carstatus);
            dto.setColor(color);
            dto.setPrice(price);
            dto.setViewcount(Integer.valueOf(viewcount));
            dto.setTitle(title);
            dto.setEmission(emission);
            dto.setShowmileage(Float.valueOf(showmileage));
            dto.setFirsthand(firsthand);
            dto.setPower(power);
            dto.setSeecarplace(seecarplace);
            dto.setOwnerdepict(ownerdepict);
            if (brands != null && brands.size() > 0) {
                dto.setBrandid(brands.get(0).getId());
            }
            if (models != null && models.size() > 0) {
                dto.setModel(models.get(0).getId());
            }
            dto.setCity(shtCity.getId());
            dto.setProvinces(shtProvince != null ? shtProvince.getId() : null);
            dto.setAreaid(shtDistrict != null ? shtDistrict.getId() : null);
            StringBuilder sb = new StringBuilder();
            sb.append(brandName).append(modelName).append(cardtime).append(price).append(showmileage);
            dto.setKeyword(sb.toString());
            dto.setPlatform(EnumPlatform.DATA_OUMAN.getCode());
            //            truckService.save(dto);
            truckService.update(dto);
            newid = dto.getId();
            ouman.setEnterupdatetime(new Date());
            ouman.setHasSave(HAS_SAVE);
            truckOumanMapper.update(ouman);
        } else {
            dto = transformToTruck(ouman);
            truckService.save(dto);
            newid = dto.getId();
            ouman.setEnterupdatetime(new Date());
            ouman.setRelationId(newid);
            ouman.setHasSave(HAS_SAVE);
            ouman.setEnterupdatetime(new Date());
            truckOumanMapper.update(ouman);
        }

        Truck tk = truckService.get(newid);
        if (tk != null) {
            saveInfoid(tk);
            saveTruckImages(imgList, tk);
        }
    }

    private void saveTruckImages(String imgList, Truck tk) {
        if (StringUtils.isNotBlank(imgList)) {
            //设置图片表里的deltag=1,已删除
            imgDtoService.deleteByTruckid(tk.getId());
            JSONArray array = JSONArray.parseArray(imgList);
            List<TruckImgDto> imgDtos = new ArrayList<>();
            for (Object anArray : array) {
                JSONObject object = (JSONObject) anArray;
                TruckImgDto truckImgDto = new TruckImgDto();
                //[{"fileName":"/upload/upload/20160322/c0927b34-509a-48cb-a77e-daa126fa4a1d.jpg","originalName":"1.jpg"},{"fileName":"/upload/upload/20160322/2f3692c6-818f-4349-9d22-3656843f8abc.jpg","originalName":"封面同步图片"}]
                String location = IMG_PREFIX + object.getString("fileName");
                String name = object.getString("originalName");
                truckImgDto.setCid(tk.getId());
                truckImgDto.setDeltag("0");
                truckImgDto.setImgpath(location);
                truckImgDto.setLocation("0");
                truckImgDto.setCreateDate(new Date());
                truckImgDto.setIsthumbnail("0");
                imgDtos.add(truckImgDto);
            }

            if (imgDtos.size() > 0) {
                try {
                    imgDtoService.batchSave(imgDtos);
                    //                    LOGGER.info("图片信息更新成功");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    LOGGER.error(ex.getMessage());
                }
            }
        }
    }

    private Date formatDate(String datestr) throws ParseException {
        if(StringUtils.isBlank(datestr)){
            return null;
        }
        return datestr.length() <= 10 ? DateUtil.defaultFormatStringToDate(datestr + " 00:00:00") :
                defaultFormatStringToDate(datestr);
//        return StringUtils.isNotBlank(datestr) ? DateUtils.parseDate(datestr, "yyyy-MM-dd HH:mm:ss") : null;
    }

    private TruckOuman testObject(JSONObject result) {
        String modelname = result.getString("modelName");
        String firsthand = result.getString("firsthand");
        String updatetime = result.getString("updatetime");
        String imglist = result.getString("imgList");
        String emission = result.getString("emission");
        String tel = result.getString("contacttel");
        String carstatus = result.getString("carstatus");
        String contact = result.getString("contactname");
        String createtime = result.getString("createtime");
        Long id = result.getLong("id");
        String username = result.getString("username");
        String title = result.getString("title");
        String provincename = result.getString("provinceName");
        String vin = result.getString("vin");
        String power = result.getString("power");
        String showmileage = result.getString("showmileage");
        String imgthumbnail = result.getString("imgthumbnail");
        String brandname = result.getString("brandName");
        String usertype = result.getString("userType");
        String viewcount = result.getString("viewcount");
        Float price = result.getFloat("price");
        String ownerdepict = result.getString("ownerdepict");
        String address = result.getString("address");
        String color = result.getString("color");
        String cityname = result.getString("cityName");
        String cardtime = result.getString("cardtime");
        String areaname = result.getString("areaname");
        Long truckid = result.getLong("truckId");

        TruckOuman ouman = new TruckOuman();
        //        ouman.setTruckId(id);
        ouman.setId(id);
        ouman.setEntercreatetime(new Date());
        ouman.setContactname(contact);
        ouman.setContacttel(tel);
        ouman.setCreatetime(createtime);
        ouman.setUpdatetime(updatetime);
        ouman.setAreaname(areaname);
        ouman.setModelName(modelname);
        ouman.setFirsthand(firsthand);
        ouman.setImgList(imglist);
        ouman.setEmission(emission);
        ouman.setCarstatus(carstatus);
        ouman.setUsername(username);
        ouman.setUserType(usertype);
        ouman.setTitle(title);
        ouman.setProvinceName(provincename);
        ouman.setVin(vin);
        ouman.setPower(power);
        ouman.setShowmileage(showmileage);
        ouman.setImgThumbnail(IMG_PREFIX + imgthumbnail);
        ouman.setBrandName(brandname);
        ouman.setViewcount(viewcount);
        ouman.setPrice(price);
        ouman.setOwnerdepict(ownerdepict);
        ouman.setColor(color);
        ouman.setCityName(cityname);
        ouman.setCardtime(cardtime);
        ouman.setTruckId(truckid);
        ouman.setEnterupdatetime(new Date());
        ouman.setSource(SOUCE_OUMAN);
        ouman.setHasSave(NOT_SAVE);
        return ouman;
    }


    public TruckOuman getTruckOumanByTruckIdAndSource(Long truckId, String source) {
        return truckOumanMapper.getOumanBySourceAndOumanId(source, truckId);
    }

}
